package com.jetlion.douyinapiexample.controller;

import com.jetlion.douyinapiexample.dto.WebHookDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/douyin")
@Slf4j
public class DouyinWebHooksController {


    @GetMapping("/getDouyinAcccessToken")
    public String getDouyinAcccessTokenGet(HttpServletRequest request,String code,String state) {
        String ip = getRemoteHost(request);
        log.info("Get ip===>" + ip);
        log.info("code===>" + code);
        log.info("state===>" + state);
        return ip;
    }

    @PostMapping("/getDouyinAcccessToken")
    public String getDouyinAcccessTokenPost(HttpServletRequest request,String code,String state) {
        String ip = getRemoteHost(request);
        log.info("post ip===>" + ip);
        log.info("code===>" + code);
        log.info("state===>" + state);
        return ip;
    }

    @PostMapping("/WebHooks")
    public Map WebHooks(@RequestBody WebHookDTO webHookDTO, HttpServletRequest request) {
        String ip = getRemoteHost(request);
        log.info("WebHooks ip===>" + ip);
        log.info("webHookDTO===>" + webHookDTO);
        int challenge = webHookDTO.getContent().getChallenge();
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("challenge", challenge);
        return res;
    }

    /**
     * TODO //获得客户端的主机名
     *
     * @param request
     * @return
     * @author yqwang
     * @date 2017年2月22日 下午3:55:27
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

}
